﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTOFrameworks;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using FooFun.DataElements.Dtos;

namespace FooFun.Web.Controls
{
    [ParseChildren(true), PersistChildren(false)]
    public class EnumerableElementView : Control, IDataElementBinder
    {

        public EnumerableElementView()
        {
            this.ChildControlsCreated = false;
        }
        #region IDataElementBinder 成员

        IDataElement dataElement;

        public IDataElement DataElement
        {
            get { return dataElement; }
            set { dataElement = value; }
        }

        #endregion

        ITemplate itemTemplate;

        [
            Browsable(false),
            PersistenceMode(PersistenceMode.InnerProperty),
            Description("普通项模板"),
            TemplateContainer(typeof(DataElementWebControl))
        ]
        public ITemplate ItemTemplate
        {
            get { return itemTemplate; }
            set
            {
                itemTemplate = value;
            }
        }

        public override ControlCollection Controls
        {
            get
            {
                //EnsureChildControls();
                return base.Controls;
            }
        }

        protected override void CreateChildControls()
        {
            this.Controls.Clear();
            if (ItemTemplate != null)
            {
                foreach (IDataElement de in this.DataElement)
                {
                    DataElementWebControl ctr
                        = new DataElementWebControl();

                    itemTemplate.InstantiateIn(ctr);

                    this.Controls.Add(ctr);

                    ctr.DataElement = de;
                    ctr.DataBind();
                }
            }

            this.ChildControlsCreated = true;
        }

    }

    public class DataElementWebControl : Control, INamingContainer, IDataElementBinder
    {
        #region IDataElementBinder 成员

        IDataElement dataElement;

        public IDataElement DataElement
        {
            get { return dataElement; }
            set { dataElement = value; }
        }

        #endregion
    }

    public interface IDataElementBinder
    {
        IDataElement DataElement
        {
            get;
            set;
        }
    }
}
